﻿using System;
using System.ComponentModel;
using System.Deployment.Application;
using System.Diagnostics;
using System.Windows.Forms;

namespace CloudShot.Utils
{
	public static class ApplicationUpdater
	{
		public static void InstallUpdateIfAvailable()
		{
			//http://msdn.microsoft.com/en-us/library/ms404263.aspx
			if (!ApplicationDeployment.IsNetworkDeployed)
				return;

			try
			{
				ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
				ad.CheckForUpdateCompleted += OnCheckOfUpdateCompleted;
				ad.CheckForUpdateAsync();
			}
			catch (Exception err)
			{
				Trace.TraceError("Message: {0}\r\nType:{1}\r\nDate: {2}\r\nStackTrace: {3}\r\n", err.Message, err.GetType().FullName, DateTime.Now, err.StackTrace);
			}
		}

		private static void OnCheckOfUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e)
		{
			try
			{
				if (!e.UpdateAvailable)
					return;

				ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
				ad.UpdateCompleted += OnUpdateCompleted;
				ad.UpdateAsync();
			}
			catch (Exception err)
			{
				Trace.TraceError("Message: {0}\r\nType:{1}\r\nDate: {2}\r\nStackTrace: {3}\r\n", err.Message, err.GetType().FullName, DateTime.Now, err.StackTrace);
			}
		}

		private static void OnUpdateCompleted(object sender, AsyncCompletedEventArgs e)
		{
			if (e.Cancelled)
				return;
						
			MessageBox.Show("The application has been upgraded, and will now restart.");
			Application.Restart();
		}
	}
}
